<template>
  <div class="container">
    <div class="form-container">
      <el-card>
        <header class="header">
          <div v-if="isEdit">编辑员工信息</div>
          <div v-else-if="isCreate">新建员工信息</div>
          <div v-else-if="isCheck">员工信息</div>
        </header>
        <section class="main">
          <el-form :model="staffForm" ref="form" label-width="120px" style="width: 500px; margin: 0 auto; text-align: left">
            <el-form-item label="姓名：" class="label" prop="staffName">
              <el-input placeholder="请输入" v-model="staffForm.staffName" :disabled="isCheck"></el-input>
            </el-form-item>
            <el-form-item label="性别：" class="label" prop="gender">
              <el-radio v-model="staffForm.gender" :label="0" :disabled="isCheck">女</el-radio>
              <el-radio v-model="staffForm.gender" :label="1" :disabled="isCheck">男</el-radio>
            </el-form-item>
            <el-form-item label="出生日期：" class="label" prop="birthday">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="staffForm.birthday"
                type="date"
                placeholder="选择出生日期"
                :disabled="isCheck">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="手机号：" class="label" prop="phoneNumber">
              <el-input placeholder="请输入" v-model="staffForm.phoneNumber" maxlength="11" :disabled="isCheck"></el-input>  
            </el-form-item>
            <el-form-item label="邮箱：" class="label" prop="email">
              <el-input placeholder="请输入" v-model="staffForm.email" :disabled="isCheck"></el-input>  
            </el-form-item>
            <el-form-item label="工作城市：" class="label" prop="workCity">
              <div style="display: flex; aligin-items: center">
                <el-select v-model="province" placeholder="请选择省" :clearable="true" style="padding-right: 5px;" :disabled="isCheck">
                  <el-option
                    v-for="item in Area"
                    :key="item.value"
                    :label="item.label"
                    :value="item">
                  </el-option>
                </el-select>
                <el-select v-model="city" placeholder="请选择市" :clearable="true" style="padding-left: 5px;" :disabled="isCheck">
                  <el-option
                    v-for="item in cityQuery"
                    :key="item.value"
                    :label="item.label"
                    :value="item">
                  </el-option>
                </el-select>
                <!-- <el-select v-model="area" placeholder="请选择区" :clearable="true">
                  <el-option
                    v-for="item in areaQuery"
                    :key="item.value"
                    :label="item.label"
                    :value="item">
                  </el-option>
                </el-select> -->
              </div>
            </el-form-item>
            <el-form-item label="部门：" class="label" prop="department">
              <el-input placeholder="请输入" v-model="staffForm.department" :disabled="isCheck"></el-input>
            </el-form-item>
            <el-form-item label="职位：" class="label" prop="role">
              <el-input placeholder="请输入" v-model="staffForm.role" :disabled="isCheck"></el-input>
            </el-form-item>
            <el-form-item label="职能：" class="label" prop="roleFunction">
              <el-input placeholder="请输入" type="textarea" :rows="2" v-model="staffForm.roleFunction" :disabled="isCheck"></el-input>  
            </el-form-item>
            <el-form-item label="月薪：" class="label" prop="salary">
              <el-input placeholder="请输入" v-model="staffForm.salary" :disabled="isCheck">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="在职状态：" class="label" prop="staffStatus">
              <el-switch
                v-model="staffForm.staffStatus" :disabled="isCheck">
              </el-switch>  
            </el-form-item>
            <div v-if="isCheck" style="text-align: center">
              <el-button size="small" @click="onCancel">返回</el-button>
            </div>
            <div v-else class="flex" style="width: 300px; margin: 0 auto">
              <el-button size="small" @click="onCancel">取消</el-button>
              <el-button type="primary" size="small" @click="submitForm('form')">提交</el-button>
            </div>
          </el-form>
        </section>
      </el-card>
    </div>
  </div>
</template>
<script>
import { fetchStaffDetail, addStaff, updateStaff } from '@/api/staffCenter.js'
export default {
  name: 'StaffForm',
  data() {
    return {
      isEdit: /edit/g.test(window.location.href),
      isCreate: /create/g.test(window.location.href),
      isCheck: /detail/g.test(window.location.href),
      staffForm: {
        staffID: '',
        staffName: '',
        role: '',
        gender: '',
        birthday: '',
        roleFunction: '',
        department: '',
        workCity: '',
        phoneNumber: '',
        email: '',
        salary: '',
        unit: '北京理工大学',
        staffStatus: false,
      },
      Area:[],
      cityQuery:[],
      areaQuery:[],
      province: {
        label: '',
      },
      city: {
        label: '',
      },
      initCity: undefined,
      area: '',
    }
  },
  watch:{
    // 监听省级
    province: function(newValue) {
      this.city = '';
      this.area = '';
      this.cityQuery=[];
      this.areaQuery =[];
      this.Area.forEach((item) => {
        if (newValue.label === item.label) {
          this.cityQuery = item.children;
        }
      })
      if (this.initCity) {
        this.city = this.initCity;
        this.initCity = undefined;
      }
    },
    // 监听市级
    city:function(newValue) {
      this.areaQuery =[];
      this.area="";
      this.cityQuery.forEach((item) => {
        if (newValue.label === item.label) {
          this.areaQuery = item.children;
        }
      })
    },
  },
  created() {
    // load area information
    this.Area = require('@/utils/area.json');
    if (this.$route.query.staffID) {
      fetchStaffDetail(this.$route.query.staffID).then((res) => {
        if (res.data.code === 20000) {
          this.staffForm = res.data.data;
          const {staffStatus, workCity } = res.data.data;
          this.staffForm.staffStatus = staffStatus === 1 ? true : false;
          const areaArray = workCity.split("-");
          // find province item in array
          const provinceArr = this.Area.filter((item) => {
            return item.label === areaArray[0];
          });
          this.province = provinceArr[0];
          // fill the city
          const filterCityArr = this.cityQuery.filter((item) => {
            return item.label = areaArray[1];
          });
          this.initCity = filterCityArr[0];
        }
      }).catch((error) => {
        console.log(error);
      })
    }
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    submitForm(formName) {
      const label = this.isEdit ? '编辑成功' : '创建成功';
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //调用接口
          let payload = this.staffForm;
          payload.staffStatus = this.staffForm.staffStatus ? 1 : 0;
          payload.workCity = this.province.label + '-' + this.city.label;
          payload.birthday = this.staffForm.birthday;
          let formdata = new FormData();
          formdata.append("staffID", payload.staffID);
          formdata.append("staffName", payload.staffName);
          formdata.append("role", payload.role);
          formdata.append("gender", payload.gender);
          formdata.append("birthday", payload.birthday);
          formdata.append("roleFunction", payload.roleFunction);
          formdata.append("department", payload.department);
          formdata.append("phoneNumber", payload.phoneNumber);
          formdata.append("workCity", payload.workCity);
          formdata.append("email", payload.email);
          formdata.append("salary", payload.salary);
          formdata.append("unit", payload.unit);
          formdata.append("staffStatus", payload.staffStatus);
          if (this.isEdit) {
            payload.staffID = this.$route.query.staffID;
            updateStaff(formdata);
          } else {
            addStaff(formdata);
          }

          this.$confirm('员工信息可前往人员管理页面进行查看', label, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success',
            center: true
          }).then(() => {
            this.$message({
              type: 'success',
              message: label
            })
            this.$router.push('/staff-center');
          })
        } else {
          this.$message({
            message: '提交失败，请仔细检查内容！',
            type: 'warning',
          })
          return false;
        }
      })
    },
    onCancel() {
      this.$router.push('/staff-center');
      this.resetForm('form');
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  .form-container {
    width: 1200px;
    margin: 20px auto;
  }
  .header{ 
    height: 50px;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
  }
}
.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
<style>
.el-form-item__label {
  font-weight: 600;
}
</style>
